<!--
 * @Author: 杨光辉_GerhardYang
 * @Date: 2020-11-14 00:49:08
 * @LastEditors: 杨光辉(GerhardYang)
 * @LastEditTime: 2021-06-05 00:08:35
 * @Description: file content
-->
<template>
  <div>
    <a-card
      :title="title"
      size="small"
      class="clumap"
      style="width: 300px"
      v-show="visiable"
    >
      <a-icon
        type="question-circle"
        slot="extra"
        style="margin-right: 6px"
        title="数据较多，放大地图到14级开始显示"
      />
      <a slot="extra" href="#" title="关闭聚合展示" @click="onClose">
        <a-icon type="close" />
      </a>
      <a-radio-group
        v-model="value"
        button-style="solid"
        size="small"
        @change="onChange"
      >
        <a-radio-button value="clu">聚合图</a-radio-button>
        <a-radio-button value="heat">热力图</a-radio-button>
        <a-radio-button value="grid">格网图</a-radio-button>
      </a-radio-group>
    </a-card>
    <a-modal
      title="Title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p>{{ ModalText }}</p>
    </a-modal>
  </div>
</template>

<script>
import L from "leaflet";

import axios from "axios";
import "leaflet.markercluster";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/MarkerCluster.css";

let mapv = require("mapv");

export default {
  data() {
    return {
      title: "专题图显示图层：公共资源",
      visiable: false,
      selected_layer: null,
      nodelayerID: null,
      btnId: "rightLayers",
      popupOpendFeature: null,
      popupOpendMarker: null,
      value: "clu",
    };
  },
  computed: {
    map() {
      return this.$store.state.map;
    },
    treeClusterFeatureGroup() {
      return this.$store.state.treeClusterFeatureGroup;
    },
  },
  mounted() {},
  methods: {
    onClose() {
      this.visiable = false;
      this.map.off("moveend");
      this.treeClusterFeatureGroup.clearLayers();
    },
    // 注册监听
    onMapState() {
      this.map.on("moveend", () => {
        if (this.selected_layer) {
          console.log("moveend", this.map.getZoom(), this.selected_layer);
          if (this.map.getZoom() < 13) {
            this.treeClusterFeatureGroup.clearLayers();
            return;
          } else {
            this.treeClusterFeatureGroup.clearLayers();
            this.boundsQuery();
          }
        }
      });
    },
    boundsQuery() {
      console.log(this.selected_layer);
      let selected_layer = this.selected_layer;
      let data;
      if (selected_layer.type == "root") {
        data = {
          from: 0,
          size: 500,
          query: {
            bool: {
              should: [
                {
                  geo_bounding_box: {
                    location: {
                      top_left: {
                        lat: this.map.getBounds()._northEast.lat,
                        lon: this.map.getBounds()._southWest.lng,
                      },
                      bottom_right: {
                        lat: this.map.getBounds()._southWest.lat,
                        lon: this.map.getBounds()._northEast.lng,
                      },
                    },
                  },
                },
              ],
            },
          },
        };
      } else if (selected_layer.type == "node") {
        data = {
          from: 0,
          size: 500,
          query: {
            bool: {
              must: [
                {
                  query_string: {
                    query: selected_layer.key,
                    analyze_wildcard: false,
                    default_field: selected_layer.esDl,
                  },
                },
              ],
              should: [
                {
                  geo_bounding_box: {
                    location: {
                      top_left: {
                        lat: this.map.getBounds()._northEast.lat,
                        lon: this.map.getBounds()._southWest.lng,
                      },
                      bottom_right: {
                        lat: this.map.getBounds()._southWest.lat,
                        lon: this.map.getBounds()._northEast.lng,
                      },
                    },
                  },
                },
              ],
            },
          },
        };
      }
      // 开始查询
      axios
        .post(selected_layer.url, data)
        .then((res) => {
          let hits = res.data.hits.hits;
          // console.log(res);
          if (this.value == "clu") {
            let geojsonMarkerOptions = {
              radius: 8,
              fillColor: selected_layer.color,
              color: "#000",
              weight: 1,
              opacity: 1,
              fillOpacity: 1,
            };

            let nodelayer = new L.MarkerClusterGroup({
              spiderfyOnMaxZoom: false,
              showCoverageOnHover: true,
              zoomToBoundsOnClick: false,
              disableClusteringAtZoom: 17,
            });

            for (let item of hits) {
              let m = L.circleMarker(
                [item._source.location.lat, item._source.location.lon],
                geojsonMarkerOptions
              ).bindTooltip(`${item._source[selected_layer.esName]}`);

              m.on("click", () => {
                this.$store.state.Details.visiable = true;
                let tabledata = [];
                for (let key in item._source) {
                  if (key == "location") {
                    tabledata.push({
                      key: key,
                      value: `[${item._source[key].lat.toFixed(
                        3
                      )},${item._source[key].lon.toFixed(3)}]`,
                    });
                  } else if (!key.startsWith("SM")) {
                    tabledata.push({
                      key: key,
                      value: item._source[key],
                    });
                  }
                }
                this.$store.state.Details.data = tabledata;
              });

              nodelayer.addLayer(m);
            }
            if (this.map.getZoom() > 12) {
              nodelayer.addTo(this.treeClusterFeatureGroup);
            }
          } else if (this.value == "heat") {
            let radius = 30;
            let heatPoints = [];

            for (let item of hits) {
              heatPoints.push([
                item._source.location.lat,
                item._source.location.lon,
              ]);
            }

            let heatLayer = L.heatLayer(heatPoints, {
              radius: radius,
              minOpacity: 0.5,
            }).addTo(this.treeClusterFeatureGroup);

            if (this.map.getZoom() > 12) {
              heatLayer.addTo(this.treeClusterFeatureGroup);
            }
          } else if (this.value == "grid") {
            let layerOptions = this.getGridOptions();

            let data = [];
            for (let item of hits) {
              data.push({
                geometry: {
                  type: "Point",
                  coordinates: [
                    item._source.location.lon,
                    item._source.location.lat,
                  ],
                },
                count: 30 * Math.random(),
              });
            }
            var dataSet = new mapv.DataSet(data);

            let gridLayer = L.supermap.mapVLayer(dataSet, layerOptions, {
              noWrap: true,
            });
            if (this.map.getZoom() > 12) {
              gridLayer.addTo(this.treeClusterFeatureGroup);
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    onChange(e) {
      console.log("radio checked", e.target.value);
      this.treeClusterFeatureGroup.clearLayers();
      this.boundsQuery();
    },
    getGridOptions() {
      return {
        fillStyle: "rgba(55, 50, 250, 0.8)",
        shadowColor: "rgba(255, 250, 50, 1)",
        shadowBlur: 20,
        max: 100,
        size: 50,
        unit: "px", // unit可选值['px', 'm']，默认值为'px'
        label: {
          show: true,
          fillStyle: "black",
        },
        globalAlpha: 0.7,
        gradient: {
          0.25: "rgb(0,0,255)",
          0.55: "rgb(0,255,0)",
          0.85: "rgb(255,255,0)",
          1.0: "rgb(255,0,0)",
        },
        draw: "honeycomb",
      };
    },
  },
};
</script>
<style lang="less" scoped>
.clumap {
  position: absolute;
  z-index: 129;
  top: 65px;
  right: 330px;
  width: 140px;
}
</style>
